<template>
    <el-card class="card">
        <el-form :inline="true">
            <el-form-item label="用户名：">
                <el-input v-model="username" placeholder="请输入搜索的用户名" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getUserList()">搜索</el-button>
                <el-button type="primary" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card style="margin-top: 20px;">
        <el-row>
            <el-col>
                <el-button type="primary" @click="addUser" v-btnFlag="`btn.User.add`">新增用户</el-button>
                <el-button type="danger" @click="delUserDg" v-btnFlag="'btn.User.remove'"
                    :disabled="idList.length == 0">批量删除</el-button>
            </el-col>
        </el-row>
        <el-table @selection-change="handleSelectionUserChange" style="margin: 10px 0px;" border :data="userArr">
            <el-table-column type="selection" align="center"></el-table-column>
            <el-table-column label="#" align="center" type="index"></el-table-column>
            <el-table-column label="ID" align="center" prop="id"></el-table-column>
            <el-table-column label="用户名字" align="center" prop="username" show-overflow-tooltip></el-table-column>
            <el-table-column label="用户名称" align="center" prop="name" show-overflow-tooltip></el-table-column>
            <el-table-column label="用户角色" align="center" prop="roleName" show-overflow-tooltip></el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip></el-table-column>
            <el-table-column label="更新时间" align="center" prop="updateTime" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" width="300px" align="center">
                <template #="{ row, }">
                    <el-button type="primary" size="small" icon="User" @click="setRole(row)">分配角色</el-button>
                    <el-button type="primary" size="small" icon="Edit" @click="updateUser(row)">编辑</el-button>
                    <el-popconfirm :title="`你确定要删除${row.username}?`" width="260px" @confirm="deleteUser(row.id)">
                        <template #reference>
                            <el-button type="primary" size="small" icon="Delete">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[5, 7, 9]" :background="true"
            layout=" prev, pager, next, jumper,->, sizes,total" :total="total" @size-change="getUserList()"
            @current-change="getUserList" />
    </el-card>
    <el-drawer v-model="drawerUser" @close="useCancel">
        <template #header>
            <h4>{{ userData.id ? '编辑用户' : '添加用户' }}</h4>
        </template>
        <template #default>
            <el-form :model="userData" ref="refUser" :rules="useRules" label-width="100px" class="demo-ruleForm">
                <el-form-item label="用户姓名" prop="username">
                    <el-input v-model="userData.username" placeholder="请输入用户姓名" />
                </el-form-item>
                <el-form-item label="用户昵称" prop="name">
                    <el-input v-model="userData.name" placeholder="请输入用户昵称" />
                </el-form-item>
                <el-form-item v-if="!userData.id" label="用户密码" prop="password">
                    <el-input v-model="userData.password" placeholder="请输入用户密码" />
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="useCancel">取消</el-button>
                <el-button type="primary" @click="useConfrim">确定</el-button>
            </div>
        </template>
    </el-drawer>
    <el-drawer v-model="drawerRole" @close="roleCancel">
        <template #header>
            <h4>角色分配</h4>
        </template>
        <template #default>
            <el-form>
                <el-form-item label="用户姓名">
                    <el-input v-model="userData.username" disabled placeholder="请输入用户姓名" />
                </el-form-item>
                <el-form-item label="职位列表">
                    <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate"
                        @change="handleCheckAllChange">全选</el-checkbox>
                    <el-checkbox-group v-model="checkedRoles" @change="handleCheckedRolesChange">
                        <el-checkbox v-for=" role  in  roles " :key="role.id" :label="role">{{
                            role.roleName
                        }}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>

            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="roleCancel">取消</el-button>
                <el-button type="primary" @click="roleConfrim">确定</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script setup lang="ts">
import { getUser, addOrUpdateUser, removeUser, toAssign, doAssignRole, batchRemove } from '@/api/art/user';
import { onMounted, ref, reactive } from 'vue'
import type { ReturnUsers, User, ReturnRoles, Role } from '@/api/art/user/type'
import { ElMessage } from 'element-plus';
import settingState from '@/store/modules/setting';
const setState = settingState()

// 是否全选角色
const checkAll = ref<boolean>(false)
const isIndeterminate = ref<boolean>(true)
// 选中的角色
const checkedRoles = ref<Role[]>([])
// 所有角色
const roles = ref<Role[]>([])

const username = ref<string>('')
const pageNo = ref<number>(1)
const pageSize = ref<number>(5)
const total = ref<number>(0)
// c抽屉
const drawerUser = ref<boolean>(false)
const drawerRole = ref<boolean>(false)
// 用户列表
const userArr = ref<User[]>([])
// 用户请求
let userData = reactive<User>({
    username: '',
    password: '',
    name: ''
})

// 需要删除用户的多个id
const idList = ref<any>([])
// 表单实例
const refUser = ref()
onMounted(() => {
    getUserList()
})
// 获取用户列表
const getUserList = async (page: number = 1) => {
    pageNo.value = page
    // console.log(pageNo.value, pageSize.value, username.value)
    const data: ReturnUsers = await getUser(pageNo.value, pageSize.value, username.value)
    userArr.value = data.data.records
    total.value = data.data.total
}
// 添加用户
const addUser = () => {
    userData.id = 0
    drawerUser.value = true
}
// 自定义校验
const validateUserName = (rule: any, value: any, callback: any) => {
    if (value.trim().length >= 5) {
        callback()
    } else {
        callback(new Error("用户名至少5位"))
    }
}
const validatePass = (rule: any, value: any, callback: any) => {
    if (value.trim().length >= 6) {
        callback()
    } else {
        callback(new Error("密码至少6位"))
    }
}
const validateName = (rule: any, value: any, callback: any) => {
    if (value.trim().length >= 5) {
        callback()
    } else {
        callback(new Error("密码至少5位"))
    }
}
// 校验规则
const useRules = {
    username: [
        {
            required: true, trigger: 'blur', validator: validateUserName,
        }
    ],
    password: [
        {
            required: true, trigger: 'blur', validator: validatePass,
        }
    ],
    name: [
        {
            required: true, trigger: 'blur', validator: validateName,
        }
    ]
}
// 取消
const useCancel = () => {
    refUser.value.resetFields()
    drawerUser.value = false
    Object.assign(userData, {
        username: '',
        password: '',
        name: ''
    })

}
// 确定新增编辑
const useConfrim = () => {
    refUser.value.validate(async (valid: any) => {
        if (!valid) return
        const data = await addOrUpdateUser(userData)
        if (data.code == 200) {
            ElMessage.success(userData.id ? "编辑用户成功！" : "添加用户成功！")
            getUserList()

        } else {
            ElMessage.error(userData.id ? "编辑用户失败！" : "添加用户失败！")
        }
        useCancel()
    })
}
// 分配角色
const setRole = async (row: User) => {
    Object.assign(userData, row)
    const data: ReturnRoles = await toAssign(row.id as number)
    if (data.code == 200) {
        roles.value = data.data.allRolesList
        checkedRoles.value = data.data.assignRoles
    }
    drawerRole.value = true

}
// 角色是否全选及取消
const handleCheckAllChange = (val: boolean) => {
    checkedRoles.value = val ? roles : [] as any
    isIndeterminate.value = false
}
// 点击复选框
const handleCheckedRolesChange = (val: Role[]) => {
    const valCount = val.length
    checkAll.value = valCount === roles.value.length
    isIndeterminate.value = valCount > 0 && valCount < roles.value.length
}
// 编辑用户
const updateUser = (row: User) => {
    drawerUser.value = true
    userData = row
}
// 删除管理用户！
const deleteUser = async (id: number) => {
    const data = await removeUser(id)
    if (data.code == 200) {
        ElMessage.success("删除管理用户成功！")
        getUserList(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
    } else {
        ElMessage.error("删出管理用户失败！")
    }
}
// 取消角色分配
const roleCancel = () => {
    drawerRole.value = false
}
// 确定角色分配
const roleConfrim = async () => {
    const data = await doAssignRole({
        roleIdList: checkedRoles.value.map(item => item.id),
        userId: userData.id as number
    })
    console.log(data)
    if (data.code == 200) {
        ElMessage.success("角色分配成功！")
        getUserList(pageNo.value)
        roleCancel()
    } else {
        ElMessage.error("角色分配失败！")
    }
}
// 批量删除
const handleSelectionUserChange = (val: User[]) => {
    idList.value = val.map(item => item.id)
}
// 删除一个或多个
const delUserDg = async () => {
    const data = await batchRemove(idList.value)
    if (data.code == 200) {
        ElMessage.success("删除成功！")
        getUserList(pageNo.value)
    } else {
        ElMessage.error("删除失败！")
    }
}
// 重置
const reset = () => {
    setState.mainFlag = !setState.mainFlag
}
</script>
<script lang="ts">
export default {
    name: 'User'
}
</script>
<style scoped lang="scss">
.card {
    height: 80px;

    .el-form {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}
</style>